package com.ls.utils.sms;

import com.alibaba.fastjson.JSON;
import com.ls.config.redis.RedisClient;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.entity.Customer;
import com.ls.entity.Linkman;
import com.ls.entity.SmsRecord;
import com.ls.service.ICustomerService;
import com.ls.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ls.constant.SystemConstants.*;
import static com.ls.constant.SystemConstants.SMS_STATUS_SENDING;

/**
 * Created by pengyu on 2020/4/6.
 * 短信余额扣除工具类
 */
@Slf4j
@Component
public class ReduceSmsUtil {
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private RedisClient redisClient;
    public static final Integer MAX_CONTENT =67;
    private static final Pattern SHORT_LINK_PATTERN =
            Pattern.compile("(?i)(https?:\\/\\/)?(www\\.)?mhw9\\.cn\\/\\S+");
    public void reduceSms(Long customerId, String content, ResultData result, Linkman linkman,Long pRecordId,Integer templateCategory,Long holidayId,Integer callType,Integer sendStatus,Integer type) {
        log.info("短信余额扣除工具类");
        log.info("会员ID：{}", customerId);
        log.info("短信内容：{}", content);
        log.info("短信内容长度：{}", content.length());
        log.info("接收人员：{}", linkman);
        Integer number = reduceNum(content);
        log.info("短信条数：{}", number);
        Customer customer = customerService.getById(customerId);
        Integer smsSource=0;
        //判断从哪里扣除
        if (customer.getMessageNum() >=number && customer.getSmsThaliNum() >=number) {
            // 获取会员有效期
            LocalDateTime memberExpire = customer.getMemberExpireTime();
            // 比较两个有效期（处理可能的null值）
            boolean useSmsPackage = customer.getSmsClearTime().isAfter(memberExpire);
            if (useSmsPackage) {
                customer.setMessageNum(customer.getMessageNum() - number);
                smsSource=1;
            } else {
                customer.setSmsThaliNum(customer.getSmsThaliNum() - number);
                smsSource=2;
            }
        } else if (customer.getMessageNum() >=number) {
            customer.setMessageNum(customer.getMessageNum() - number);
            smsSource=1;
        } else if (customer.getSmsThaliNum() >=number) {
            customer.setSmsThaliNum(customer.getSmsThaliNum() - number);
            smsSource=2;
        }
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setPRecordId(pRecordId);
        Integer recordId = (Integer) result.getData();
        smsRecord.setRecordId(recordId.longValue());
        smsRecord.setCustomerId(customer.getCustomerId());
        smsRecord.setCustomerPhone(customer.getPhone());
        if (linkman!=null){
            smsRecord.setOuterPhone(linkman.getLinkmanPhone());
            smsRecord.setOuterName(linkman.getLinkmanName());
        }
        smsRecord.setCallType(callType);
        smsRecord.setHolidayId(holidayId);
        smsRecord.setSmsType(CHANNEL_TYPE_PLATFORM);
        smsRecord.setTemplateCategory(templateCategory);
        smsRecord.setContent(content);
        smsRecord.setSendStatus(sendStatus);
        LocalDateTime now = LocalDateTime.now();
        smsRecord.setCreateTime(now);
        smsRecord.setSendTime(now);
        //失败
        if (!result.isSuccess()) {
            smsRecord.setSmsStatus(SMS_STATUS_FALSE);
            smsRecord.setSmsSource(0);
            smsRecord.setSmsReduceNum(0);
        } else {
            smsRecord.setSmsStatus(SMS_STATUS_SENDING);
            smsRecord.setSmsSource(smsSource);
            log.info("短信记录扣除条数：{}",number);
            smsRecord.setSmsReduceNum(number);
            customer.setSmsTotal(customer.getSmsTotal() - number);
            customer.setCurrentSendTimes(customer.getCurrentSendTimes() + 1);
            customer.setPlatformSendTimes(customer.getPlatformSendTimes() + 1);
            customer.setSendTimes(customer.getSendTimes() + 1);
            customer.setLastSendTime(now);
            customer.updateById();
            if (type==1){
                String cacheKey = APP + "_" + customer.getCustomerId();
                // 使用标准JSON序列化
                redisClient.save(cacheKey, JSON.toJSONString(customer));
            }
        }
        smsRecord.insert();
    }
    public Integer reduceNum(String content) {
        boolean hasShortLink = containsShortLink(content);
        Integer number = ((content.length() + MAX_CONTENT - 1) / MAX_CONTENT) + (hasShortLink ? 1 : 0);
        log.info("短信内容包含短链接：{}，短信条数：{}", hasShortLink, number);
        return number;
    }

    private boolean containsShortLink(String content) {
        Matcher matcher = SHORT_LINK_PATTERN.matcher(content);
        return matcher.find();
    }
}
